package com.zzyl.job;

import cn.hutool.json.JSONUtil;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class AlertJob {

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AlertRuleService alertRuleService;

    @Scheduled(cron = "0 * * * * ?")
    public void deviceDataAlertFilter() {
        //查询所有报警规则
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null, null, null);
        //判断是否为空，如果为空直接退出;
        if (alertRules == null || alertRules.isEmpty()) {
            return;
        }


        //查询所有设备上传的数据
        Set<String> keys = redisTemplate.keys("Iot:Device:*");
        //没有数据直接退出
        if (keys == null || keys.isEmpty()) {
            return;
        }

        //存储redis中所有设备上报的数据
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        //将数据进行格式化处理
        keys.forEach(key -> {
            String s = redisTemplate.opsForValue().get(key);
            List<DeviceDataVo> deviceDataVoList1 = JSONUtil.toList(s, DeviceDataVo.class);
            deviceDataVoList.addAll(deviceDataVoList1);
        });

        //遍历然后传入数据报警处理器
        deviceDataVoList.forEach(deviceDataVo -> {
            alertRuleService.alertFilter(deviceDataVo);
        });
    }

}
